package com.tang.calculator;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: Context
 * @Author: freedu
 * @Date: 2021/3/19 16:47
 * @Description: TODO
 * @Version: 1.0
 */
@Data
@Slf4j
public class Context {
    private String type;
    private String operate;
    private String path;
    private boolean end = false;

    private List<CalculateProcessor> list;

    public boolean isEnd(){
        return end;
    }

    /**
     * 需要操作的数据
     */
    private List<DataSource> dataSources = new LinkedList<>();

    /**
     * 执行器
     */
    private CalculateProcessor processor;

    public Context(String type, String operate){
        this.type = type;
        this.operate = operate;
    }

    public Context setDataSource(String mode, String operate, Map<String, Object> data, Class<?> sourceType){
        DataSource dataSource = new DataSource();
        dataSource.setMode(mode);
        dataSource.setSource(data);
        dataSource.setOperate(operate);
        dataSource.setSourceType(sourceType);
        dataSource.setConfigPath("/FormulaConfig.json");
//        this.jointConfigPath();
        dataSources.add(dataSource);
        return this;
    }

    public List<Map<String, Object>> getDataSourceMap(){
        List<Map<String, Object>> mapList = dataSources.stream().map(DataSource::getSource).collect(Collectors.toList());
        return mapList;
    }

    public List<Object> getDataSourceList(){
        List<Object> list = dataSources.stream().flatMap(m -> m.getSource().values().stream()).collect(Collectors.toList());
        return list;
    }

    public List<DataSource> getDataSourceByType(Class<?> clazz) {
        List<DataSource> list = dataSources.stream().filter(f -> f.getSourceType() == clazz).collect(Collectors.toList());
        return list;
    }

    public void run() {
        if (dataSources == null || dataSources.isEmpty()) {
            throw new RuntimeException("数据不能为空!");
        }
        processor.process(this);
    }

    private void jointConfigPath(){
        // TODO
        log.info("拼接配置文件路径");
        this.path = "/FormulaConfig.json";
    }
}

